<template>
  <!-- <div> {{ imgBase64 }}---</div> -->
  <div>
    <input v-if="!imgBase64" ref="fileInput" type="file" accept="image/png,image/jpeg" @change="handleChange" />
    <div v-else class="avatarImg">
      <el-button class="closeBtn" type="primary" link :icon="Close" @click="clearImg" />
      <img :src="imgBase64" alt="" srcset="" height="120px" width="120px" />
    </div>
  </div>
</template>

<script setup>
import { ref, defineProps, defineEmits, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import {
  Close
} from '@element-plus/icons-vue'
import { uploadAvatarApi } from '../../request/resume_api'
const props = defineProps({
  // ['avatarId', 'avatar']
  avatarId: { type: String, require: false },
  avatar: { type: String, require: false }
})
const emit = defineEmits(['clearAvatar', 'editAvatar'])
// const imgBase64 = ref('')
const imgBase64 = computed(() => {
  return props.avatar
})
const fileInput = ref(null)
const handleChange = async () => {
  if (fileInput.value.files[0].size > 1038576 * 2) {
    ElMessage({
      message: '图片体积过大',
      type: 'warning'
    })
  } else {
    const imageFile = new FileReader()
    const fileData = fileInput.value.files[0]
    imageFile.readAsDataURL(fileData)
    imageFile.onload = () => {
      imgBase64.value = imageFile.result
    }
    const formData = new FormData()
    formData.append('file', fileInput.value.files[0])
    formData.append('avatarId', props.avatarId)
    const res = await uploadAvatarApi(formData)
    if (res.code === 200) {
      emit('editAvatar', imageFile.result)
    }
    console.log('-----fileInput', formData)
    console.log('-----res', res)
  }
}
// watch(props.avatar, (newVal, oldVal) => {
//   console.log('--a------', newVal, oldVal)
//   imgBase64.value = newVal
// }, { deep: true, immediate: true })

const clearImg = () => {
  emit('clearAvatar')
}
// const editAvatar = () => {
//   emit('editAvatar')
// }
onMounted(() => {
  console.log('-----props.avatar--', props.avatar)
  // imgBase64.value = props.avatar
})
</script>

<style lang="less" scoped>
.avatarImg {
  position: relative;

  .closeBtn {
    position: absolute;
    top: 0;
    left: 100px;
  }
}
</style>
